<template>
  <div>
    <van-field
      v-model="telcode"
      center
      clearable
      placeholder="请输入手机验证码"
    >
      <template #button>
        <van-button size="small" type="primary" :disabled="flag" @click="verificationCode">{{text}}{{count}}</van-button>
      </template>
    </van-field>
    <van-button round class="btn" block color="#ff6666" :disabled="nextflag" @click="next">下一步</van-button>
  </div>
</template>

<script>
import Vue from 'vue'
import { NavBar, Field, Button } from 'vant'
import { doCheckCode, doSendMsgCode } from '../../api/user.js'

Vue.use(doCheckCode)
Vue.use(doSendMsgCode)
Vue.use(NavBar)
Vue.use(Field)
Vue.use(Button)

export default {
  data () {
    return {
      nextflag: true,
      flag: true,
      telcode: '',
      text: '发送验证码',
      count: 2,
      timer: null
    }
  },
  watch: {
    telcode (newV) {
      // console.log(newV)
      if (newV.length === 5) {
        this.nextflag = false
      } else {
        this.nextflag = true
      }
    }
  },
  mounted () {
    this.sendCode()
  },
  methods: {
    async sendCode () {
      this.count = 2
      this.timer = setInterval(() => {
        this.count--
        if (this.count === 0) {
          clearInterval(this.timer)
          this.text = '重新发送'
          this.count = ''
          this.flag = false
        }
      }, 1000)
      const noteCode = await doSendMsgCode({ tel: localStorage.getItem('tel') })
      // console.log(noteCode.data.code) // 成功状态 200
      console.log(noteCode) // 验证码
    },
    verificationCode () {
      this.flag = true
      this.sendCode()
    },
    async next () {
      const checkCode = await doCheckCode({ tel: localStorage.getItem('tel'), telcode: this.telcode })
      console.log(checkCode)
      console.log(checkCode.data.code)
      if (checkCode.data.code === '200') {
        this.$router.push('/step0/step3')
      } else {
        console.log('验证码输入错误')
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
.content
  padding 30px 20px
.van-button--small
  width 90px
</style>
